package com.haoyanbing.easyexcel;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author liurui
 * @date 2023/4/14 13:40
 */
public class DateConverter implements com.alibaba.excel.converters.Converter<Date> {

    private static final String PATTERN_YYYY_MM_DD = "yyyy-MM-dd hh:mm:hh";
    private static final String regex1 = "(\\w{3})\\s+(\\d{1,2}),\\s+(\\d{4})";//"Feb 1, 2022"
    private static final String regex2 = "(\\d{1,2})-(\\w{3})-(\\d{2})";       //"1-jan-22"
    private static final String regex3 = "^(\\d{4})/(\\d{1,2})/(\\d{1,2})$"; // 2022/12/1
    private static final String regex4 = "^[\u4e00-\u9fa5]{2,3}\\s\\d{2},\\s\\d{4}$";  // Mar 01, 2022
    private static final SimpleDateFormat formatter0 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
    private static final SimpleDateFormat formatter1 = new SimpleDateFormat("d-MMM-yy", Locale.ENGLISH);
    private static final SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/M/d", Locale.ENGLISH);
    private static final SimpleDateFormat formatter3 = new SimpleDateFormat("MMM dd, yyyy", Locale.CHINA);

    @Override
    public Class<?> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String str = cellData.getStringValue();
        if (str.matches(regex1)) {
            return formatter0.parse(str);
        } else if (str.matches(regex2)) {
            return formatter1.parse(str);
        } else if (str.matches(regex3)) {
            Date parsedDate = formatter2.parse(str);
            return parsedDate;
        } else if (str.matches(regex4)) {
            Date date = formatter3.parse(str);
            return date;
        } else {
            throw new RuntimeException("时间格式不匹配 " + str);
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        String dateValue = sdf.format(value);
        return new WriteCellData<>(dateValue);
    }
}